package com.mxw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mxw.entity.UserInfo;
import com.mxw.mapper.UserInfoMapper;
import com.mxw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    @Transactional
    public UserInfo register(UserInfo userInfo) {
        // 参数校验
        if (userInfo == null || !StringUtils.hasText(userInfo.getUserName()) 
            || !StringUtils.hasText(userInfo.getPassword()) 
            || !StringUtils.hasText(userInfo.getEmail())) {
            return null;
        }

        // 检查用户名和邮箱是否已存在
        if (isUserNameExists(userInfo.getUserName()) || isEmailExists(userInfo.getEmail())) {
            return null;
        }

        // 设置默认值
        userInfo.setCreateTime(new Date());
        userInfo.setModifyTime(new Date());
        userInfo.setPushAdv(1); // 默认开启广告推送
        userInfo.setUserId(System.currentTimeMillis()); // 使用时间戳作为userId

        // 保存用户信息
        userInfoMapper.insert(userInfo);
        
        // 清除密码后返回
        userInfo.setPassword(null);
        return userInfo;
    }

    @Override
    public boolean isUserNameExists(String userName) {
        if (!StringUtils.hasText(userName)) {
            return false;
        }
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserName, userName);
        return userInfoMapper.selectCount(wrapper) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        if (!StringUtils.hasText(email)) {
            return false;
        }
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getEmail, email);
        return userInfoMapper.selectCount(wrapper) > 0;
    }

    @Override
    public UserInfo login(String userName, String password) {
        if (!StringUtils.hasText(userName) || !StringUtils.hasText(password)) {
            return null;
        }

        // 根据用户名查询用户
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserName, userName);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);

        // 验证用户存在且密码正确
        if (userInfo != null && password.equals(userInfo.getPassword())) {
            // 清除密码后返回
            userInfo.setPassword(null);
            return userInfo;
        }

        return null;
    }
} 